<script lang="ts" setup>
import type { LowcodeTableConfigApi } from '#/api/lowcode/table-config';

import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useVbenModal } from '@vben/common-ui';
import { message } from 'ant-design-vue';

import { getTableConfigPage } from '#/api/lowcode/table-config';
import { getDatasourceConfigPage, getEnabledDatasourceList } from '#/api/lowcode/datasource';

interface Emits {
  (e: 'success'): void;
}

const emit = defineEmits<Emits>();
const router = useRouter();

// 弹窗控制
const visible = ref(false);
const loading = ref(false);

// 表格列表数据
const tableList = ref<LowcodeTableConfigApi.CodegenTable[]>([]);
const filteredTableList = computed(() => {
  return tableList.value.filter(item => 
    searchValue.value === '' || 
    item.tableName.toLowerCase().includes(searchValue.value.toLowerCase()) ||
    (item.tableComment && item.tableComment.includes(searchValue.value))
  );
});

// 搜索
const searchValue = ref('');

// 选中的表
const selectedTableId = ref<number>();

// 加载表格列表
async function loadTableList() {
  loading.value = true;
  try {
    const { data } = await getTableConfigPage({
      pageNo: 1,
      pageSize: 999,
    });
    
    tableList.value = data.list || [];
  } catch (error) {
    console.error('加载表格列表失败:', error);
    message.error('加载表格列表失败');
  } finally {
    loading.value = false;
  }
}

// 选择表格
function selectTable(table: LowcodeTableConfigApi.CodegenTable) {
  selectedTableId.value = table.id;
}

// 生成页面
async function generatePage() {
  if (!selectedTableId.value) {
    message.warning('请选择一个表格');
    return;
  }
  
  const selectedTable = tableList.value.find(item => item.id === selectedTableId.value);
  if (!selectedTable) return;
  
  try {
    // 构建通用页面URL
    const url = `/lowcode/generic?tableName=${selectedTable.tableName}&configId=${selectedTable.id}&dataSourceId=${selectedTable.dataSourceConfigId || 0}`;
    
    // 在新标签页中打开
    window.open(url, '_blank');
    
    message.success(`已为表 "${selectedTable.tableName}" 生成通用管理页面`);
    
    // 关闭弹窗
    visible.value = false;
    emit('success');
  } catch (error) {
    console.error('生成页面失败:', error);
    message.error('生成页面失败');
  }
}

// 打开弹窗
function open() {
  visible.value = true;
  selectedTableId.value = undefined;
  searchValue.value = '';
  loadTableList();
}

// 关闭弹窗
function close() {
  visible.value = false;
}

defineExpose({
  open,
  close,
});
</script>

<template>
  <a-modal
    v-model:open="visible"
    title="快速生成通用页面"
    width="800px"
    :confirm-loading="loading"
    @ok="generatePage"
    @cancel="close"
  >
    <div class="py-4">
      <!-- 搜索框 -->
      <div class="mb-4">
        <a-input
          v-model:value="searchValue"
          placeholder="搜索表名或注释"
          allow-clear
          class="w-full"
        />
      </div>
      
      <!-- 表格列表 -->
      <div class="max-h-96 overflow-y-auto">
        <a-spin :spinning="loading">
          <div v-if="filteredTableList.length === 0" class="text-center py-8 text-gray-500">
            暂无数据
          </div>
          <div v-else class="space-y-2">
            <div
              v-for="table in filteredTableList"
              :key="table.id"
              class="p-3 border rounded cursor-pointer hover:bg-gray-50 transition-colors"
              :class="{
                'border-blue-500 bg-blue-50': selectedTableId === table.id,
                'border-gray-200': selectedTableId !== table.id
              }"
              @click="selectTable(table)"
            >
              <div class="flex items-center justify-between">
                <div>
                  <div class="font-medium text-gray-900">
                    {{ table.tableName }}
                  </div>
                  <div class="text-sm text-gray-500 mt-1">
                    {{ table.tableComment || '无注释' }}
                  </div>
                </div>
                <div class="text-right text-sm text-gray-400">
                  <div>更新时间</div>
                  <div>{{ new Date(table.updateTime).toLocaleDateString() }}</div>
                </div>
              </div>
              
              <div class="flex items-center gap-4 mt-2 text-xs text-gray-500">
                <span>数据源: {{ table.dataSourceConfigId ? `自定义(${table.dataSourceConfigId})` : '默认' }}</span>
                <span>模板类型: {{ table.templateType === 1 ? 'CRUD' : '树形' }}</span>
                <span>场景: {{ table.scene === 1 ? '管理后台' : '用户 APP' }}</span>
              </div>
            </div>
          </div>
        </a-spin>
      </div>
      
      <div v-if="selectedTableId" class="mt-4 p-3 bg-blue-50 border border-blue-200 rounded">
        <div class="flex items-center text-blue-700">
          <span>已选择表: {{ tableList.find(t => t.id === selectedTableId)?.tableName }}</span>
        </div>
        <div class="text-sm text-blue-600 mt-1">
          点击确定将在新标签页中打开该表的通用管理页面
        </div>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.ant-modal-body {
  max-height: 60vh;
  overflow-y: auto;
}
</style>